import {
  GetTokenizerAsync,
  UpdateTokenizer,
  ExistsTokeninerByName,
  DeleteTokenizerById,
  GetExtendWord,
  UpdateExtendWord,
  DeleteExtendWord,
  GetDisableWord,
  UpdateDisableWord,
  DeleteDisableWord,
  GetSynonymWord,
  UpdateSynonymWord,
  DeleteSynonymWord,
  GetAnalyzerByText,
} from '../servers';
import {
  Space,
  Modal,
  Table,
  Input,
  Form,
  ConfigProvider,
  message,
  Button,
} from 'antd';
import {
  useState,
  useMemo,
  useEffect,
  useImperativeHandle,
  forwardRef,
  Ref,
} from 'react';
import { ExclamationCircleFilled } from '@ant-design/icons';
import { getMessage, TextWidget } from '@inbiz/react';
import type { ColumnsType } from 'antd/es/table';
import Pagination from '@inbiz/basic/Pagination';
import { GlobalRegistry } from '@inbiz/core';
import { observer } from '@formily/react';
const { confirm } = Modal;
import moment from 'moment';
import { Widget } from '@antv/x6/lib/addon/common';
const { TextArea } = Input;

const TableList = forwardRef((props: any, ref: any) => {
  const { activeTab, setSelectLine, GetPage, search, tableList, getTableList } = props;
  const [form] = Form.useForm();

  // 存储点击行数据
  const [storeData, setStoreData] = useState<DataType[]>([]);

  // 编辑弹出框
  const [edit, setEdit] = useState(false);

  // 正则分词编辑弹出框
  const [regularEdit, setRegularEdit] = useState(false);

  // 页码
  const [pageIndex, setPageIndex] = useState(1);

  // 页数
  const [pageSize, setPageSize] = useState(parseInt(GetPage));

  // 数据总数
  const [dataTotal, setDataTotal] = useState(0);

  // 存储接口数据
  // const [tableList, setTableList] = useState([]);

  // 加载中
  const [loading, setLoading] = useState(false);

  // 正则测试结果
  const [analyzerText, setAnalyzerText] = useState([]);

  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  // 多语言
  const synset = getMessage('WordSegmentationManagement.synset');
  const extendedWord = getMessage('WordSegmentationManagement.extendedWord');
  const stopWord = getMessage('WordSegmentationManagement.stopWord');
  const regularName = getMessage('WordSegmentationManagement.regularName');
  const common = getMessage('WordSegmentationManagement.common');
  const strip = getMessage('WordSegmentationManagement.strip');
  const exist = getMessage('WordSegmentationManagement.exist');
  interface DataType {
    text: any;
    KeyWord: any;
    TokenizerRule: any;
    TokenizerDesc: any;
    TokenizerName: any;
    key: React.Key;
    name: string;
    age: number;
    address: string;
    Id: any;
    renderName: any;
  }
  // 多语言
  const totalinfo = useMemo(() => {
    return getMessage('WordSegmentationManagement.totalinfo')
  }, [GlobalRegistry.getDesignerLanguage()])
  // 表格列
  const columns: ColumnsType<DataType> = [
    {
      title:
        activeTab == 'synonym'
          ? synset
          : activeTab == 'extendedWord'
            ? extendedWord
            : activeTab == 'stopWord'
              ? stopWord
              : regularName,
      dataIndex:
        activeTab == 'regularWordSegmentationConfiguration'
          ? 'TokenizerName'
          : 'KeyWord',
      width: '30%',
      ellipsis: true,
    },
    {
      title: getMessage('WordSegmentationManagement.operator'),
      dataIndex: 'OperatorName',
      width: '200px',
    },
    {
      title: getMessage('WordSegmentationManagement.operationTime'),
      dataIndex: 'CreateTime',
      width: 180,
      render: (t) => {
        if (t) {
          return moment(t).format('YYYY-MM-DD HH:mm:ss');
        } else {
          return '';
        }
      },
    },
    {
      title: getMessage('WordSegmentationManagement.operate'),
      dataIndex: 'address',
      width: 200,
      render: (_, record) => (
        <Space size="middle">
          <a
            onClick={(e) => {
              activeTab == 'regularWordSegmentationConfiguration'
                ? setRegularEdit(true)
                : setEdit(true),
                setStoreData([record]);
              // 表单数据回显
              form.setFieldsValue({
                TokenizerName: record.TokenizerName,
                TokenizerRule: record.TokenizerRule,
                TokenizerDesc: record.TokenizerDesc,
                KeyWord: record.KeyWord,
                text: record.text,
              });
            }}
          >
            <TextWidget>WordSegmentationManagement.edit</TextWidget>
          </a>
          <a
            onClick={() => {
              showDeleteConfirm(record), setStoreData([record]);
            }}
          >
            <TextWidget>WordSegmentationManagement.delete</TextWidget>
          </a>
        </Space>
      ),
    },
  ];



  if (activeTab == 'regularWordSegmentationConfiguration') {
    columns.splice(
      1,
      0,
      {
        title: getMessage('WordSegmentationManagement.regularRules'),
        dataIndex: 'TokenizerRule',
        width: '30%'
      },
      {
        title: getMessage('WordSegmentationManagement.describe'),
        dataIndex: 'TokenizerDesc',
        width: '30%'
      },
    );
  }


  // 重置分页
  useEffect(() => {
    setPageIndex(1);
  }, [search]);


  // 判断分词器是否可用
  const ExistsTokeniner = (callback?: Function) => {
    form.validateFields().then((_res: any) => {
      ExistsTokeninerByName(_res.TokenizerName)
        .then((res: any) => {
          callback && callback(res);
        })
        .catch((err: any) => {
          console.log(err);
        });
    });
  };

  // 确定编辑
  const editOk = () => {
    form.validateFields().then((_res: any) => {
      let params = {
        Id: storeData?.map((item: any) => item?.Id),
        ..._res,
      };

      switch (activeTab) {
        case 'synonym':
          UpdateSynonymWord(params)
            .then((res: any) => {

              if (res?.Code == 0) {
                setEdit(false);
                message.success(
                  getMessage('WordSegmentationManagement.successfullyModified'),
                );
                getTableList();
              }
              else if (res?.Code == 1) {
                message.error(
                  storeData[0].Id + getMessage('WordSegmentationManagement.noEmpty')
                );
              } else if (res?.Code == 2) {
                form.setFields([
                  {
                    name: 'KeyWord',
                    errors: [getMessage(
                      `WordSegmentationManagement.cannotBeEmpty`,
                      {
                        0: _res.KeyWord,
                      }
                    )]
                  },
                ]);
              } else if (res?.Code == 3) {
                message.error(
                  storeData[0].Id + getMessage('WordSegmentationManagement.dataNoFound')
                );
              } else if (res?.Code == 4) {
                form.setFields([
                  {
                    name: 'KeyWord',
                    errors: [`${_res.KeyWord}` + exist],
                  },
                ]);
              } else {
                message.error(
                  getMessage('WordSegmentationManagement.modificationFailed'),
                );
              }
              // if (res?.Code == 0) {
              //   setEdit(false);
              //   message.success(
              //     getMessage('WordSegmentationManagement.successfullyModified'),
              //   );
              //   getTableList();
              // } else if (res?.Code == 1) {
              //   form.setFields([
              //     {
              //       name: 'KeyWord',
              //       errors: [`${_res.KeyWord}已存在`],
              //     },
              //   ]);
              // } else {
              //   message.error(
              //     getMessage('WordSegmentationManagement.modificationFailed'),
              //   );
              // }
            })
            .catch((err: any) => {
              console.log(err);
            });
          break;
        case 'extendedWord':
          UpdateExtendWord(params)
            .then((res: any) => {
              if (res?.Code == 0) {
                setEdit(false);
                message.success(
                  getMessage('WordSegmentationManagement.successfullyModified'),
                );
                getTableList();
              }
              else if (res?.Code == 1) {
                message.error(
                  storeData[0].Id + getMessage('WordSegmentationManagement.noEmpty')
                );
              } else if (res?.Code == 2) {
                form.setFields([
                  {
                    name: 'KeyWord',
                    errors: [getMessage(
                      `WordSegmentationManagement.cannotBeEmpty`,
                      {
                        0: _res.KeyWord,
                      },
                    ),],
                  },
                ]);
              } else if (res?.Code == 3) {
                message.error(
                  storeData[0].Id + getMessage('WordSegmentationManagement.dataNoFound')
                );
              } else if (res?.Code == 4) {
                form.setFields([
                  {
                    name: 'KeyWord',
                    errors: [`${_res.KeyWord}` + exist],
                  },
                ]);
              } else {
                message.error(
                  getMessage('WordSegmentationManagement.modificationFailed'),
                );
              }
            })
            .catch((err: any) => {
              console.log(err);
            });
          break;
        case 'stopWord':
          UpdateDisableWord(params)
            .then((res: any) => {
              if (res?.Code == 0) {
                setEdit(false);
                message.success(
                  getMessage('WordSegmentationManagement.successfullyModified'),
                );
                getTableList();
              }
              else if (res?.Code == 1) {
                message.error(
                  storeData[0].Id + getMessage('WordSegmentationManagement.noEmpty')
                );
              } else if (res?.Code == 2) {
                form.setFields([
                  {
                    name: 'KeyWord',
                    errors: [getMessage(
                      `WordSegmentationManagement.cannotBeEmpty`,
                      {
                        0: _res.KeyWord,
                      },
                    ),],
                  },
                ]);
              } else if (res?.Code == 3) {
                message.error(
                  storeData[0].Id + getMessage('WordSegmentationManagement.dataNoFound')
                );
              } else if (res?.Code == 4) {
                form.setFields([
                  {
                    name: 'KeyWord',
                    errors: [`${_res.KeyWord}` + exist],
                  },
                ]);
              } else {
                message.error(
                  getMessage('WordSegmentationManagement.modificationFailed'),
                );
              }
            })
            .catch((err: any) => {
              console.log(err);
            });
          break;
        case 'regularWordSegmentationConfiguration':

          UpdateTokenizer(params).then((res: any) => {
            if (res?.Code == 0) {
              // 修改成功
              setRegularEdit(false);
              message.success(
                getMessage('WordSegmentationManagement.successfullyModified'),
              );
              getTableList();
            }
            else if (res?.Code == 2) {
              // 分词器名称不允许为空
              form.setFields([
                {
                  name: 'TokenizerName',
                  errors: [getMessage(`WordSegmentationManagement.regularWord2`,)]
                },
              ]);
            } else if (res?.Code == 3) {
              // 分词器名称与系统内置分词器名称重复
              form.setFields([
                {
                  name: 'TokenizerName',
                  errors: [getMessage(
                    `WordSegmentationManagement.regularWord3`
                  )]
                },
              ]);
            } else if (res?.Code == 4) {
              // 分词规则不允许为空
              form.setFields([
                {
                  name: 'TokenizerRule',
                  errors: [getMessage(
                    `WordSegmentationManagement.regularWord4`
                  )]
                },
              ]);
            } else if (res?.Code == 5) {
              // 已存在当前分词器名称
              form.setFields([
                {
                  name: 'TokenizerName',
                  errors: [getMessage(
                    `WordSegmentationManagement.regularWord5`
                  )]
                },
              ]);
            } else if (res?.Code == 6) {
              // 数据不存在
              message.error(getMessage(`WordSegmentationManagement.regularWord6`))
            } else if (res?.Code == 7) {
              // 当前分词正在使用中不允许编辑
              form.setFields([
                {
                  name: 'TokenizerName',
                  errors: [getMessage(
                    `WordSegmentationManagement.regularWord7`
                  )]
                },
              ]);
            }else {
              message.error(
                getMessage(
                  'WordSegmentationManagement.modificationFailed',
                ),
              );
            }

          });
          break;
      }
    });
  };

  // 测试
  const handleTest = () => {
    form.validateFields().then((res: any) => {
      GetAnalyzerByText(res)
        .then((_res: any) => {
        for(let i=0;i<_res.length;i++){
          _res[i]+='\n'
        }
            setAnalyzerText(_res.toString().replace(/,/g,''));
        })
        .catch((err: any) => {
          console.log(err);
        });
    });
  };
  useEffect(()=>{
    setAnalyzerText([])
  },[regularEdit])

  useEffect(() => {
    form.setFieldValue('TokenizerResult', analyzerText)
  }, [analyzerText])

  const handleCancel = () => {
    // 清空测试
    setAnalyzerText([])
    // 取消/关闭编辑
    setEdit(false);
    setRegularEdit(false);
  };


  // 删除
  const showDeleteConfirm = (record: any) => {
    confirm({
      title: getMessage(
        `WordSegmentationManagement.areYouSureYouWantToDeleteTheSelected`,
        {
          0:
            activeTab == 'synonym'
              ? synset
              : activeTab == 'extendedWord'
                ? extendedWord
                : activeTab == 'stopWord'
                  ? stopWord
                  : regularName,
        },
      ),
      icon: <ExclamationCircleFilled />,
      content: getMessage(
        'WordSegmentationManagement.afterEeletionTheRelevantDataWillNotBeRecoverable',
      ),
      className: 'inbiz-Word-segmentation-delModal',
      centered: true,
      okText: getMessage('WordSegmentationManagement.determine'),
      cancelText: getMessage('WordSegmentationManagement.cancellation'),
      onOk() {
        let params = {
          Id: record?.Id,
        };
        if (activeTab == 'synonym') {
          DeleteSynonymWord(params)
            .then((res: any) => {
              if (res?.Code == 0) {
                message.success(
                  getMessage('WordSegmentationManagement.successfullyDeleted'),
                );
                getTableList();
              } else {
                message.error(
                  getMessage('WordSegmentationManagement.deleteFailed'),
                );
              }
            })
            .catch((err: any) => {
              console.log(err);
            });
        } else if (activeTab == 'extendedWord') {
          DeleteExtendWord(params)
            .then((res: any) => {
              if (res?.Code == 0) {
                message.success(
                  getMessage('WordSegmentationManagement.successfullyDeleted'),
                );
                getTableList();
              } else {
                message.error(
                  getMessage('WordSegmentationManagement.deleteFailed'),
                );
              }
            })
            .catch((err: any) => {
              console.log(err);
            });
        } else if (activeTab == 'stopWord') {
          DeleteDisableWord(params)
            .then((res: any) => {
              if (res?.Code == 0) {
                message.success(
                  getMessage('WordSegmentationManagement.successfullyDeleted'),
                );
                getTableList();
              } else {
                message.error(
                  getMessage('WordSegmentationManagement.deleteFailed'),
                );
              }
            })
            .catch((err: any) => {
              console.log(err);
            });
        } else {
          ExistsTokeninerByName(record.TokenizerName).then((res: any) => {

            if (res.Code !== 0) {
              Modal.warning({
                title: record.TokenizerName + getMessage('WordSegmentationManagement.useing')
              },
              );
            } else {
              DeleteTokenizerById(params)
                .then((res: any) => {
                  setRegularEdit(false);
                  if (res?.Code == 0) {
                    message.success(
                      getMessage(
                        'WordSegmentationManagement.successfullyDeleted',
                      ),
                    );
                    getTableList();
                  } else {
                    message.error(
                      getMessage('WordSegmentationManagement.deleteFailed'),
                    );
                  }
                })
                .catch((err: any) => {
                  console.log(err);
                });
            }
          });
        }
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  };

  const rowSelection = {
    selectedRowKeys,
    onChange: (selectedRowKeys: React.Key[], selectedRows: DataType[]) => {
      setSelectLine(selectedRows);
      setSelectedRowKeys(selectedRowKeys);
    },
  };







  // 向外暴露的方法
  useImperativeHandle(ref, () => ({
    index: props.id,
    getTableList,
    tableList: tableList,
  }));



  return (
    <>
      <Table
        pagination={false}
        bordered
        rowSelection={{
          ...rowSelection,
        }}
        columns={columns}
        dataSource={tableList}
        rowKey="Id"
      // onRow={(record: any) => {
      //   return {
      //     onClick: (event) => {
      //       setStoreData([record]);
      //     }, // 点击行
      //   };
      // }}
      />

      {/* 编辑弹出框 */}
      {activeTab == 'regularWordSegmentationConfiguration' ? (
        <Modal
          title={getMessage('WordSegmentationManagement.edit')}
          visible={regularEdit}
          width={450}
          className="inbiz-Word-segmentation-modal inbiz-Word-segmentation-editModal"

          style={{ fontSize: '12px' }}
          bodyStyle={{
            // height: '114px',
            padding: '21.5px 40px 0px 33px',
            boxSizing: 'border-box',
          }}
          centered={true}
          onCancel={handleCancel}
          footer={[
            <Button onClick={handleCancel}>
              <TextWidget>WordSegmentationManagement.cancellation</TextWidget>
            </Button>,
            <Button loading={loading} onClick={handleTest} >
              <TextWidget>WordSegmentationManagement.test</TextWidget>
            </Button>,
            <Button type="primary" onClick={editOk}>
              <TextWidget>WordSegmentationManagement.save</TextWidget>
            </Button>,
          ]}>
          <Form
            form={form}
            name={'basic' + activeTab}
            preserve={false}
            autoComplete="off"
            labelCol={{ span: 8 }}
            wrapperCol={{ span: 17 }}
          >
            <Form.Item
              name="TokenizerName"
              label={getMessage('WordSegmentationManagement.regularName')}
              rules={[
                {
                  required: true,
                  message: getMessage(
                    'WordSegmentationManagement.regularNameCannotBeEmpty',
                  ),
                },
                {
                  max: 30,
                  message: getMessage(
                    'WordSegmentationManagement.cannotExceed30Characters',
                  ),
                },
              ]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              name="TokenizerRule"
              label={getMessage('WordSegmentationManagement.regularRules')}
              rules={[
                {
                  required: true,
                  message: getMessage(
                    'WordSegmentationManagement.regularRulesCannotBeEmpty',
                  ),
                },
              ]}
            >
              <Input
                placeholder={getMessage(
                  'WordSegmentationManagement.pleaseEnterARegularExpression',
                )}
              />
            </Form.Item>
            <Form.Item
              name="TokenizerDesc"
              label={getMessage('WordSegmentationManagement.describe')}
              rules={[
                {
                  max: 100,
                  message: getMessage(
                    'WordSegmentationManagement.cannotExceed100Characters',
                  ),
                },
              ]}
            >
              <Input
                placeholder={getMessage(
                  'WordSegmentationManagement.pleaseEnterADescription',
                )}
              />
            </Form.Item>
            <Form.Item
              name="text"
              label={getMessage('WordSegmentationManagement.testText')}
            >
              <TextArea
                placeholder={getMessage(
                  'WordSegmentationManagement.Enter1',
                )}
                autoSize={{ minRows: 5 }}
              />
            </Form.Item>
            <Form.Item
              name="TokenizerResult"
              label={getMessage('WordSegmentationManagement.testResult')}
            >
              <TextArea
                autoSize={{ minRows: 5 }}
                placeholder={getMessage(
                  'WordSegmentationManagement.Enter1',
                )}
              />
            </Form.Item>
          </Form>
        </Modal>
      ) : (
        <Modal
          title={getMessage('WordSegmentationManagement.edit')}
          visible={edit}
          width={450}
          onOk={editOk}
          style={{ fontSize: '12px' }}
          bodyStyle={{
            padding: '25.184px 40px 0px 33px',
            boxSizing: 'border-box',
          }}
          centered={true}
          // onOk={handleUpload}
          onCancel={handleCancel}
        >
          <Form
            form={form}
            name="basic"
            preserve={false}
            initialValues={{ remember: true }}
            // onFinish={onFinish}
            // onFinishFailed={onFinishFailed}
            autoComplete="off"
            labelCol={{ span: 6 }}
            wrapperCol={{ span: 18 }}
          >
            {activeTab == 'synonym' ? (
              <Form
                name={'basic' + activeTab}
                initialValues={{ remember: true }}
                autoComplete="off"
                form={form}
                preserve={false}
              >
                <Form.Item
                  name="KeyWord"
                  label={getMessage('WordSegmentationManagement.synset')}
                  rules={[
                    {
                      required: true,
                      message: getMessage(
                        `WordSegmentationManagement.cannotBeEmpty`,
                        {
                          0: synset,
                        },
                      ),
                    },
                    // 不能只是一个词
                    {
                      validator: (_, value) => {
                        let result = value
                          ?.split(',')
                          .filter((element: any) => {
                            return element !== '';
                          });
                        if (result && result.length == 1) {
                          return Promise.reject(
                            new Error(
                              getMessage(
                                'WordSegmentationManagement.theSynonymSetCannotBeJustOneWord',
                              ),
                            ),
                          );
                        } else {
                          return Promise.resolve();
                        }
                      },
                    },
                  ]}
                >
                  <TextArea
                    placeholder={getMessage(
                      'WordSegmentationManagement.useEnglishCommasToSeparateSynonyms',
                    )}
                    autoSize={{ minRows: 5 }}
                  />
                </Form.Item>
              </Form>
            ) : activeTab == 'extendedWord' ? (
              <Form
                name={'basic' + activeTab}
                initialValues={{ remember: true }}
                autoComplete="off"
                form={form}
                preserve={false}
              >
                <Form.Item
                  name="KeyWord"
                  label={getMessage('WordSegmentationManagement.extendedWord')}
                  rules={[
                    {
                      required: true,
                      message: getMessage(
                        `WordSegmentationManagement.cannotBeEmpty`,
                        {
                          0: extendedWord,
                        },
                      ),
                    },
                  ]}
                >
                  <TextArea
                    placeholder={getMessage(
                      `WordSegmentationManagement.Enter`,
                      {
                        0: extendedWord,
                      },
                    )}
                    autoSize={{ minRows: 2, maxRows: 6 }}
                  />
                </Form.Item>
              </Form>
            ) : (
              <Form
                name={'basic' + activeTab}
                initialValues={{ remember: true }}
                autoComplete="off"
                form={form}
                preserve={false}
              >
                <Form.Item
                  name="KeyWord"
                  label={getMessage('WordSegmentationManagement.stopWord')}
                  rules={[
                    {
                      required: true,
                      message: getMessage(
                        `WordSegmentationManagement.cannotBeEmpty`,
                        {
                          0: stopWord,
                        },
                      ),
                    },
                  ]}
                >
                  <TextArea
                    placeholder={getMessage(
                      `WordSegmentationManagement.Enter`,
                      {
                        0: stopWord,
                      },
                    )}
                    autoSize={{ minRows: 2, maxRows: 6 }}
                  />
                </Form.Item>
              </Form>
            )}
          </Form>
        </Modal>
      )}
    </>
  );
});

export default TableList;
